package reward

import (
	"fmt"
	"hotMoney/data"
	"hotMoney/service"
	"math/rand"
	"strconv"
	"time"
)

type Rewards struct {
	Count int				//个数
	Money int				//总金额
	RemainCount int			//剩余个数
	RemainMoney int
	BestMoney  int			//手气最佳金额
	BestMoneyIndex int		//手气最佳序号
	MoneyList []int			//拆分列表
}


func init() {
	a := &Rewards{
		Count:20,
		Money:10000,
		RemainCount:20,
		RemainMoney:10000,
	}
	err := service.InitRewardToDb(a.Money, a.Count,a.RemainCount)
	if err != nil {
		fmt.Println("the error of InitRewardToDb is: ",err)
	}
	for i:=0; a.RemainCount>0; i++ {
		money := GrabReward(a)
		id := 202108 + money
		//把积分初始化信息放入mysql
		err := service.InitRewardInfoToDb(id, money)
		if err != nil {
			fmt.Println("InitRewardInfoToDb error, the error is: ", err)
		}
		//放入未消费的积分队列(list),存放的是id
		_, err = data.SetNRewardList("NRewardList",strconv.Itoa(id))
		if err != nil {
			fmt.Println("SetNRewardList error, the err is: ",err)
		}
		//把积分具体信息放入redis，用hash表储存(id+money)
		_, err = data.SetRewardInfo("rewardInfo", strconv.Itoa(id), strconv.Itoa(money))
		if err != nil {
			fmt.Println("rewardInfo error, the err is: ",err)
		}
	}
}

func GrabReward(reward *Rewards) int {
	if reward.RemainCount <= 0 {
		panic("RemainCount <= 0")
	}
	//最后一个
	if reward.RemainCount - 1 == 0 {
		money := reward.RemainMoney
		reward.RemainCount = 0
		reward.RemainMoney = 0
		return money
	}
	//是否可以直接0.01
	if (reward.RemainMoney / reward.RemainCount) == 1 {
		fmt.Println(reward.RemainMoney / reward.RemainCount)
		money := 1
		reward.RemainMoney -= money
		reward.RemainCount--
		return money
	}

	//最大可领金额 = 剩余金额的平均值x2 = (剩余金额 / 剩余数量) * 2
	//领取金额范围 = 0.01 ~ 最大可领金额
	maxMoney := (reward.RemainMoney / reward.RemainCount) * 2
	rand.Seed(time.Now().UnixNano())
	money := rand.Intn(maxMoney)
	for money == 0 {
		//防止零
		money = rand.Intn(maxMoney)
	}
	reward.RemainMoney -= money
	//防止剩余金额负数
	if reward.RemainMoney < 0 {
		money += reward.RemainMoney
		reward.RemainMoney = 0
		reward.RemainCount = 0
	} else {
		reward.RemainCount--
	}
	return money
}

